import sys
import uuid
from bot.enterprise_wechat_gpt.config.conf import *

pro_path = os.path.dirname(os.path.realpath(__file__))
sys.path.append(pro_path)

from util_tool.conversation_util import ConversationUtil
from transfer_util import *
from constant_role_name import *
from common.constants import *
from utter_postprocess import hidden_character


class ConversationHistory(object):
    def __init__(self):
        self.cu = ConversationUtil()
        self.tair_util = TairUtil()
        self.welcome_msg = """🎀哈喽，本月借款有机会享受额度和利率调整\n\n⭕您本次成功从企微专属链接借款，让系统了解您的资金需求，请问你需要使用多少额度 打算借多久解决哪方面的问题呢？"""

    # 新用户初始化
    def init(self, user_id):
        self.tair_util.add_conversation(user_id, {ASSISTANT: self.welcome_msg})

    def flush(self, user_id):
        if self.tair_util.get_conversation_history(user_id):
            logging.info("-" * 20 + '清空{}的用户对话和用户信息'.format(user_id) + "-" * 20)
            self.tair_util.flush_conversation(user_id)

    def add_dialogue(self, user_id, role, msg, msg_type='text'):
        # 新用户
        if not self.tair_util.get_conversation_history(user_id):
            logging.info("-" * 20 + "未知用户: {} ".format(user_id) + "-" * 20)
            # 新用户初始化用户对话和用户信息
            self.init(user_id)
        # 老用户
        else:
            logging.info("-" * 20 + "已知用户: {} ".format(user_id) + "-" * 20)
        # 更新用户对话
        if role == USER:
            self.tair_util.add_conversation(user_id, {role: msg, 'msg_type': msg_type})
            if env_str != "local":
                self.cu.store_qw_conversation(user_id, uuid.uuid1(), MESSAGE_TYPE_TEXT, msg, ROLE_USER)
        elif role == ASSISTANT:
            self.tair_util.add_conversation(user_id, {role: msg.get("最终话术", "Get_None_Utter!"), 'msg_type': msg_type})
            if env_str != "local":
                self.cu.store_qw_conversation(user_id, uuid.uuid1(), MESSAGE_TYPE_TEXT,
                                          json.dumps(msg, ensure_ascii=False, indent=2), ROLE_ASSISTANT)
        return self.tair_util.get_conversation_history(user_id)

    def add_system_msg(self, user_id, msg, transfer=True):
        self.tair_util.add_conversation(user_id, {'系统': msg, 'transfer': transfer, 'msgtime': int(time.time())})

    # def get_conversation_history(self, user_id):
    #     return self.tair_util.get_conversation_history(user_id)

    # def get_last_user_msg(self, user_id):
    #     msg_body = self.tair_util.get_last_msg(user_id, 1)
    #     return msg_body[USER]
    #
    # def get_last_assistant_msg(self, user_id):
    #     msg_body = self.tair_util.get_last_msg(user_id, 0)
    #     return msg_body[ASSISTANT]

    def store_conversation(self, user_id, role, msg):
        if env_str == "local":
            return
        if role == USER:
            self.cu.store_qw_conversation(user_id, uuid.uuid1(), MESSAGE_TYPE_TEXT, msg, ROLE_USER)
        elif role == ASSISTANT:
            self.cu.store_qw_conversation(user_id, uuid.uuid1(), MESSAGE_TYPE_TEXT,
                                              json.dumps(msg, ensure_ascii=False, indent=2), ROLE_ASSISTANT)

    # 相当于设为已读的概念，把最后一条消息的时间戳当做处理时间，后续取大于这个时间戳的消息
    def set_last_msg_time(self, user_id, last_msg_time):
        self.tair_util.set_expire("QW:LastMsgTime:" + user_id, str(last_msg_time), 30 * 24 * 60 * 60)
        logging.info(f"userId:[{user_id}] set_last_msg_time: " + str(last_msg_time))

    def get_last_msg_time(self, user_id):
        # if is_mark_from_agent_to_ai(user_id):
        #     logging.info(f"userId:[{user_id}] 从坐席转到机器人，set_last_msg_time: 当前时间戳-60s")
        #     # 如果从人转到机，就把最后一条消息的时间戳设为当前时间戳-60s
        #     self.set_last_msg_time(user_id, int(time.time()) - 60)
        msg_time = self.tair_util.get("QW:LastMsgTime:" + user_id)
        if msg_time is None:
            logging.info(f"userId:[{user_id}] get_last_msg_time: 0 没有处理消息历史时间, 返回0")
            return 0
        msg_time = int(msg_time)
        logging.info(f"userId:[{user_id}] get_last_msg_time: {msg_time} ")
        return msg_time

    def cache_ai_response(self, user_id, res_total):
        self.tair_util.set_expire("QW:AIResponse:" + user_id, json.dumps(res_total, ensure_ascii=False), 5 * 60 * 60)

    def get_ai_response(self, user_id):
        response = self.tair_util.get("QW:AIResponse:" + user_id)
        if response is None:
            return None
        response = json.loads(response)
        return response

    def get_user_say(self, last_msg_time, dialogue_history_list, uid):
        # 找出时间大于最后处理消息时间的用户消息，并且用","拼接成一句话
        last_msg_time_from_cache = self.get_last_msg_time(uid)
        user_messages = []
        if last_msg_time_from_cache > 0:
            for item in reversed(dialogue_history_list):
                if USER in item.keys() and item['msgtime'] > last_msg_time_from_cache:
                    user_messages.append(item[USER])
                elif ASSISTANT in item.keys():
                    break
        else:
            self.get_last_user_query(dialogue_history_list, last_msg_time, uid, user_messages)

        # 在两小时之内rpa重试，超过两小时就获取用户最后的消息了
        retry = int(time.time()) < last_msg_time + 5 * 60 * 60
        if len(user_messages) == 0 and not retry:
            self.get_last_user_query(dialogue_history_list, last_msg_time, uid, user_messages)
            logging.warning(f"userId:[{uid}] RPA重试多次, 且用户发送消息时间超过一小时, 直接获取用户最后的消息")
        msg = ",".join(user_messages[::-1])
        return msg

    def get_last_user_query(self, dialogue_history_list, last_msg_time, uid, user_messages):
        # 之前没处理过该用户的消息，那么就取坐席回复之后用户所有的消息，拼接起来
        # 初始化一个空列表来存储用户说的话
        for item in reversed(dialogue_history_list):
            if USER in item.keys():
                user_messages.append(item[USER])
                last_msg_time = item['msgtime']
            elif ASSISTANT in item.keys():
                break
        self.set_last_msg_time(uid, last_msg_time - 1)

    def get_msg_types(self, last_msg_time, dialogue_history_list, uid):
        last_msg_time_from_cache = self.get_last_msg_time(uid)
        msg_types = []
        if last_msg_time_from_cache > 0:
            for item in reversed(dialogue_history_list):
                if USER in item.keys() and item['msgtime'] > last_msg_time_from_cache:
                    msg_types.append(item['msg_type'])
                elif ASSISTANT in item.keys():
                    break
        else:
            self.get_last_user_msg_type(dialogue_history_list, last_msg_time, msg_types, uid)
        retry = int(time.time()) < last_msg_time + 5 * 60 * 60
        if len(msg_types) == 0 and not retry:
            self.get_last_user_msg_type(dialogue_history_list, last_msg_time, msg_types, uid)
            logging.warning(f"userId:[{uid}] RPA重试多次, 且用户发送消息时间超过一小时, 直接获取用户最后的消息类型")
        msg_types = msg_types[::-1]
        logging.info(f"userId:[{uid}] 消息类型: {msg_types}")
        return msg_types

    def get_last_user_msg_type(self, dialogue_history_list, last_msg_time, msg_types, uid):
        # 之前没处理过该用户的消息，那么就取坐席回复之后用户所有的消息，拼接起来
        for item in reversed(dialogue_history_list):
            if USER in item.keys():
                msg_types.append(item['msg_type'])
                last_msg_time = item['msgtime']
            elif ASSISTANT in item.keys():
                break
        self.set_last_msg_time(uid, last_msg_time - 1)


# 获取坐席最后一条消息
def get_agent_last_msg(dialogue):
    last_msg = ""
    for item in reversed(dialogue):
        if ASSISTANT in item.keys():
            last_msg = item[ASSISTANT]
            break
    return last_msg


def parse_raw_list(uid, list):
    msg_history_list = []
    i = 0
    for msg_body in list:
        if not msg_body['corpId']:
            logging.warning(f"userId:[{uid}] corpId为空")
            i += 1
            # corpId为空的消息不去除，因为有可能都是空的，比如K600420871693078503076
            # continue
        msg_type = msg_body['msgtype']
        content = json.loads(msg_body['content'])
        # 只获取文本消息
        if msg_type == 'text':
            msg = content['content']
            # 删掉甲方的机器人标识
            msg = msg.replace(" \x02\x01 ·", "")
            msg = msg.replace(hidden_character.replace(" ", ""), "")
        elif msg_type == 'image':
            msg = content.get('url', 'image')
        elif msg_type == 'emotion':
            msg = content.get('url', 'emotion')
        elif msg_type == 'voice':
            msg = content.get('url', 'voice')
        elif msg_type == 'weapp':
            msg = '小程序消息：' + content.get('title', '小程序消息')
        elif msg_type == 'file':
            msg = content.get('url', 'file')
        elif msg_type == 'video':
            msg = content.get('url', 'video')
        elif msg_type == 'revoke':
            logging.warning(f"userId:[{uid}] {msg_type} 用户撤回了一条消息, 不解析")
            continue
        elif msg_type == 'location':
            msg = content.get('title', 'location.title') + ':' + content.get('address', 'location.address')
        elif msg_type == 'link':
            msg = content.get('title', 'link.title') + ':' + content.get('description', 'link.description')
        else:
            msg = '消息类型未见过'
            logging.warning(f"userId:[{uid}] {msg_type} 消息类型未见过, 不解析")
        from_id = msg_body['from']
        user_id = msg_body['userId']
        msg_time = msg_body['msgtime']
        status = msg_body['status']
        if status == 2:
            logging.warning(f"userId:[{uid}] 消息发送失败 msg:{msg}")
        msg_time = msg_time if len(str(msg_time)) == 10 else int(msg_time / 1000)
        msg_history_list.append(
            {ASSISTANT if from_id == user_id else USER: msg, 'msg_type': msg_type, 'msgtime': msg_time})
    msg_history_list.reverse()
    if i >= 10:
        logging.warning(f"userId:[{uid}] corpId为空的消息数量超过10条")
    return msg_history_list


conversation_history_util = ConversationHistory()

if __name__ == '__main__':
    conversation_history_util.cache_ai_response('123', {
        'msgtype': 'text',
        'text': {'content': ''}
    })
    ai_response = conversation_history_util.get_ai_response('123')
    if ai_response is not None:
        print(ai_response)
    else:
        print("none")